//
//  ZKVCSwipeDetail.m
//  ZAKER
//
//  Created by yaohongchao on 16/3/10.
//  Copyright © 2016年 yaohongchao. All rights reserved.
//

#import "ZKVCSwipeDetail.h"
#import "ZKSwipeDetailCell.h"
#import "ZKSwipeDetailModel.h"
#import "UIImage+Color.h"
#import "ZKVCRead.h"

@interface ZKVCSwipeDetail ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ZKSwipeDetailCellDelegate>
@property(nonatomic,weak) UICollectionView *collctionView;
@property(nonatomic,strong) UICollectionViewFlowLayout *layout;
@property(nonatomic,strong) ZKSwipeDetailModel *swipeDetailModel;
@property(nonatomic,strong) NSMutableArray *array;
@end

@implementation ZKVCSwipeDetail

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setui];
    [self setData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden= YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setui{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.automaticallyAdjustsScrollViewInsets = NO;
    WS(weakSelf);
    CGFloat bottomViewHeight = 32;
  
    UIView *bottomView = [[UIView alloc]init];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_bottom).offset(-bottomViewHeight);
        make.left.right.bottom.equalTo(weakSelf.view);
    }];
    
    UIButton *btnBack = [[UIButton alloc]init];
    btnBack.tag = 1;
    [btnBack addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *img = [[UIImage imageNameFromeBundle:@"addRootBlock_toolbar_return"] imageWithTintColor:[UIColor grayColor]];
    [btnBack setImage:img forState:UIControlStateNormal];
    [bottomView addSubview:btnBack];
    [btnBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView).offset(5);
        make.top.equalTo(bottomView);
        make.width.height.mas_equalTo(bottomView.mas_height);
    }];
    
    UIButton *btnRefresh = [[UIButton alloc]init];
    btnRefresh.tag = 2;
    [btnRefresh addTarget:self action:@selector(refreshClick:) forControlEvents:UIControlEventTouchUpInside];
    img = [[UIImage imageNameFromeBundle:@"addRootBlock_toolbar_refresh"] imageWithTintColor:[UIColor grayColor]];
    [btnRefresh setImage:img forState:UIControlStateNormal];
    [bottomView addSubview:btnRefresh];
    [btnRefresh mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView).offset(-10);
        make.top.equalTo(bottomView);
        make.width.height.mas_equalTo(bottomView.mas_height).offset(-4);
    }];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - bottomViewHeight);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    self.layout = layout;
    UICollectionView *collctionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    collctionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:collctionView];
    collctionView.pagingEnabled = YES;
    collctionView.showsHorizontalScrollIndicator = NO;
    collctionView.delegate = self;
    collctionView.dataSource = self;
    [collctionView registerClass:[ZKSwipeDetailCell class] forCellWithReuseIdentifier:@"ReuseID"];
    self.collctionView = collctionView;
    [collctionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).offset(-bottomViewHeight);
    }];
    self.array = [NSMutableArray array];
}

-(void)setData{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        NSURL *URL = nil;
        if(self.swipeDetailModel){
            if(self.swipeDetailModel.data.info.next_url.length > 0){
                URL = [NSURL URLWithString:self.swipeDetailModel.data.info.next_url];
            }else{
                return;
            }
        }else{
            URL = [NSURL URLWithString:self.apiUrl];
        }
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        WS(weakSelf);
        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                weakSelf.swipeDetailModel = [ZKSwipeDetailModel mj_objectWithKeyValues:responseObject];
                [weakSelf proData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.collctionView reloadData];
                });
            }
        }];
        [dataTask resume];
//    });
}

#pragma mark UICollectionView delegate dataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZKSwipeDetailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReuseID" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.delegate = self;
    ZKSwipeDetailPages *page = [self.array objectWithIndex:indexPath.row];
    [cell refreshWithFrmae:page];
    if(indexPath.row == self.array.count - 2){
        [self setData];
    }
    cell.blockClick = ^(ZKSwipeDetailArticles* article){
        NSLog(@"");
        dispatch_async(dispatch_get_main_queue(), ^{
            ZKVCRead *read = [[ZKVCRead alloc]init];
            read.article = article;
            [self.navigationController pushViewController:read animated:YES];
        });
        
    };
    return cell;
}

-(void)proData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (ZKSwipeDetailArticles *article in self.swipeDetailModel.data.articles) {
        [dict setObject:article forKey:article.pk];
    }
    for (ZKSwipeDetailPages *page in self.swipeDetailModel.data.ipadconfig.pages) {
        page.arrayArticle = [NSMutableArray array];
        NSArray *pks = [page.articles componentsSeparatedByString:@","];
        for (NSString *strPk in pks) {
            ZKSwipeDetailArticles *article = [dict objectForKey:strPk];
            if(article){
                [page.arrayArticle addObject:article];
            }
        }
    }
    [self.array addObjectsFromArray:self.swipeDetailModel.data.ipadconfig.pages];
}

-(void)popVc{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)backClick:(UIButton*)btn{
    [self popVc];
}

-(void)refreshClick:(UIButton*)btn{

}

-(void)dealloc{
    self.collctionView = nil;
    self.collctionView.delegate = nil;
    self.collctionView.dataSource = nil;
}


@end
